package com.jjmmbb.anydolist;

import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jjmmbb.db.adapter.MainAdapter;
import com.jjmmbb.db.adapter.MainAdapter.OptionListener;
import com.jjmmbb.db.db.ItemManager;
import com.jjmmbb.db.pojo.Item;
import com.jjmmbb.db.scan.CaptureActivity;
import com.jjmmbb.dolist.ex.AutoLinkDialog;
import com.jjmmbb.dolist.ex.MyListView;
import com.jjmmbb.dolist.ex.MyListView.OnRefreshListener;

//https://bao-dolist.googlecode.com/svn/trunk/DoList
//xX7ZX2wn9Pr9
public class MainActivity extends BaseActivity implements OnClickListener,
		OnGroupClickListener {
	private MyListView listView;
	private MainAdapter adapter;
	private LinearLayout addContent;
	private EditText addItem;
	private TextView titleView, scanView, reflashView;
	// Button bt_refresh;
	private Button bt_add;
	private InputMethodManager imm;
	private boolean isEdit = false;

	private int currentItemPosition = -1;
	private boolean isExpand = false; // 是否有展开的项

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		titleView = (TextView) findViewById(R.id.main_title);
		scanView = (TextView) findViewById(R.id.main_scan);
		reflashView = (TextView) findViewById(R.id.main_reflash);
		addContent = (LinearLayout) findViewById(R.id.main_addContent);
		addItem = (EditText) findViewById(R.id.main_addTitle);
		bt_add = (Button) findViewById(R.id.main_addOK);

		listView = (MyListView) findViewById(R.id.main_list);

		bt_add.setOnClickListener(this);
		// titleView.setOnClickListener(this);
		listView.setOnGroupClickListener(this);

		titleView.setOnTouchListener(itemTouchListener);

		listView.setonRefreshListener(new OnRefreshListener() {
			public void onRefresh() {
				showAddView();
				listView.onRefreshComplete();
			}
		});

		// 去除三角图标
		listView.setGroupIndicator(null);

		ini();
		Util.startServer(this);
	}

	private void ini() {
		// 初始化全局信息
		DisplayMetrics dMetrics = new DisplayMetrics(); // 屏幕分辨率容器
		((WindowManager) getWindowManager()).getDefaultDisplay().getMetrics(
				dMetrics);
		ap.c.screenWidth = dMetrics.widthPixels;
		ap.c.screenHeight = dMetrics.heightPixels;
		// 获取数据库管理
		ap.c.itemManager = new ItemManager(this);
		// 读取配置文件
		Util.getPreferences(this);

		// 获取键盘管理
		imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);

		int countDoing = ap.c.itemManager.getCountDoing();
		String.format(getStr(R.string.main_count_doing_per), countDoing + "");
	}

	private void showAddView() {
		addContent.setVisibility(View.VISIBLE);
		addItem.requestFocus();
		imm.showSoftInput(addItem, 0);
		isEdit = true;
	}

	// 重新加载列表
	private void updateList() {
		if (Comm.hide_delete && Comm.hide_finish) {
			ap.c.list = ap.c.itemManager.getListOrder0();
		} else if (Comm.hide_finish) {
			ap.c.list = ap.c.itemManager.getListOrder02();
		} else if (Comm.hide_delete) {
			ap.c.list = ap.c.itemManager.getListOrder01();
		} else {
			ap.c.list = ap.c.itemManager.getListOrder();
		}
		adapter = new MainAdapter(this, ap.c.list);
		adapter.setOptionListener(optionListener);
		listView.setAdapter(adapter);
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (Comm.goFromScan) {
			Comm.goFromScan = false;
			showAddView();
			addItem.setText(Comm.decode_result);
		}
		if (null == adapter) {
			updateList();
		} else {
			adapter.notifyDataSetChanged();
		}
		titleView.clearAnimation(); // 归位
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.main_addOK:
			// 隐藏虚拟键盘
			imm.hideSoftInputFromInputMethod(addItem.getWindowToken(), 0);
			imm.hideSoftInputFromWindow(addItem.getWindowToken(), 0);

			// 加入数据库,刷新列表
			Item item = new Item();
			item.title = addItem.getText().toString();
			if (insertItem(item)) {
				// 隐藏编辑框,还原编辑框
				addContent.setVisibility(View.GONE);
				addItem.setText("");
			} else {
				toast(R.string.msg_insertError);
			}
			break;
		case R.id.main_title:
			updateList();
			toast(R.string.msg_reflashed);
			break;
		}
	}

	// 新增
	boolean insertItem(Item item) {
		isEdit = false;
		item = item.insertAndReturn(ap.c.itemManager); // 插入数据库
		if (null != item) {
			ap.c.list.add(0, item);
			adapter.notifyDataSetChanged();
			return true;
		} else {
			return false;
		}
	}

	private void cancelAdd() {
		isEdit = false;
		addContent.setVisibility(View.GONE);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			if (isExpand) {
				listView.collapseGroup(currentItemPosition);
				isExpand = false;
				return false;
			}
			if (isEdit) {
				cancelAdd();
				return false;
			} else {
				this.finish();
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	// ---------------弹出菜单-------------------------//
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.main_menu_manage:
			gotoActivity(ManageActivity.class);
			break;
		case R.id.main_menu_scan:
			gotoExistActivity(CaptureActivity.class);
			// gotoActivity(OptionActivity.class);
			break;
		case R.id.main_menu_strike:
			gotoActivity(StrikeActivity.class);
			break;
		case R.id.main_menu_about:
			gotoActivity(AboutActivity.class);
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	// ---------------滑动标题的动画-------------------------//
	private OnTouchListener itemTouchListener = new OnTouchListener() {
		int justX;// 坐标矫正

		public boolean onTouch(final View v, MotionEvent event) {
			// System.out.println("touch");
			boolean flag = true;
			int eventaction = event.getAction();
			int x = (int) event.getRawX(); // 绝对坐标
			final int left = x - justX; // 修改x方向的位置
			switch (eventaction) {
			case MotionEvent.ACTION_DOWN: // touch down so check if the
				System.out.println("ACTION_DOWN");
				justX = x - v.getLeft();
				break;
			case MotionEvent.ACTION_MOVE: // touch drag with the ball
				if (left > 10 || left < -10) {
					System.out.println("r:" + (left + v.getWidth()));
					v.layout(left, v.getTop(), left + v.getWidth(), v.getTop()
							+ v.getHeight());
					v.postInvalidate();
					flag = false;
				}
				if (left > 80) {
					reflashView.setTextColor(Color.YELLOW);
				} else {
					reflashView.setTextColor(Color.GRAY);
				}
				if (left < -80) {
					scanView.setTextColor(Color.YELLOW);
				} else {
					scanView.setTextColor(Color.GRAY);
				}
				break;
			case MotionEvent.ACTION_CANCEL:
			case MotionEvent.ACTION_UP:
				if (event.getX() > titleView.getWidth()
						- titleView.getPaddingRight()
						- titleView.getCompoundPaddingRight()) {
					MainActivity.this.openOptionsMenu();
				}
			default:
				float dist = justX - x; // 移动距离
				rebackItem(v, dist);
				if (left > 80) {
					updateList();
					toast(R.string.msg_reflashed);
				}
				if (left < -80) {
					toast("扫描记事");
					gotoExistActivity(CaptureActivity.class);
				}
				break;
			}
			return flag;
		}
	};

	// 还原item,添加动画; 移动距离太短,视为无效,恢复到原来位置
	private void rebackItem(final View v, final float dist) {
		Animation animation = new TranslateAnimation(0, dist, 0, 0);
		animation.setDuration(300);
		System.out.println(dist + "");
		animation.setAnimationListener(new AnimationListener() {
			public void onAnimationStart(Animation animation) {
				System.out.println("onAnimationStart");
			}

			public void onAnimationRepeat(Animation animation) {
			}

			public void onAnimationEnd(Animation animation) {
				System.out.println("onAnimationEnd");
				v.clearAnimation();
				// 动画结束,但view的位置并没有移动,手动移动到动画后位置
				v.layout(0, v.getTop(), v.getWidth(),
						v.getTop() + v.getHeight());
			}
		});
		v.startAnimation(animation);
	}

	// --------------工具,方法-------------------------//
	private void copyToClip(String strText) {
		android.text.ClipboardManager clipboardManager = (android.text.ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
		clipboardManager.setText(strText);
		toast(R.string.msg_copySuccess);
	}

	// 跳转编辑界面
	private void gotoItemEditActivity() {
		Bundle bundle = new Bundle();
		bundle.putString("goFromMain", "main");
		Intent intent = new Intent();
		intent.setClass(this, ItemEditActivity.class);
		intent.putExtras(bundle);
		startActivity(intent);
	}

	// @Override
	// public boolean onItemLongClick(AdapterView<?> parent, View view,
	// int position, long id) {
	// System.out.println(position);
	// ap.c.item = ap.c.list.get(position);
	// gotoItemEditActivity();
	// return false;
	// }

	@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
	@Override
	public boolean onGroupClick(ExpandableListView parent, View v,
			int groupPosition, long id) {

		if (android.os.Build.VERSION.SDK_INT >= 14) {
			// 4.0以上,添加动画
			if (listView.expandGroup(groupPosition, true)) {
				isExpand = true;
			} else {
				listView.collapseGroup(groupPosition);
				isExpand = false;
			}
		} else {
			if (listView.expandGroup(groupPosition)) {
				isExpand = true;
			} else {
				listView.collapseGroup(groupPosition);
				isExpand = false;
			}
		}

		ap.c.item = ap.c.list.get(groupPosition);

		if (currentItemPosition == groupPosition) {

			return true;
		}

		// 收起上一个展开的项
		if (currentItemPosition >= 0) {
			listView.collapseGroup(currentItemPosition);
		}
		currentItemPosition = groupPosition;

		return true;
	}

	private OptionListener optionListener = new OptionListener() {

		@Override
		public void onFirst(int groupID) {
			ap.c.item.first(ap.c.itemManager);
			updateList();
			// listView.collapseGroup(groupID);
		}

		@Override
		public void onFinish(int groupID) {
			ap.c.item.finish(ap.c.itemManager);
			adapter.notifyDataSetChanged();
			listView.collapseGroup(groupID);
		}

		@Override
		public void onDoing(int groupID) {
			ap.c.item.doing(ap.c.itemManager);
			adapter.notifyDataSetChanged();
			listView.collapseGroup(groupID);
		}

		@Override
		public void onDelete(int groupID) {
			ap.c.item.delete(ap.c.itemManager, ap.c.list);
			adapter.notifyDataSetChanged();
			listView.collapseGroup(groupID);
		}

		@Override
		public void onCopy(int groupID) {
			copyToClip(ap.c.item.title);
			listView.collapseGroup(groupID);
		}

		@Override
		public void onEdit(int groupID) {
			listView.collapseGroup(groupID);
			gotoItemEditActivity();
		}

		@Override
		public void onAutoLink(int groupID) {
			AutoLinkDialog dialog = new AutoLinkDialog(MainActivity.this,
					getStr(R.string.dialog_title_autolink), ap.c.item.title);
			dialog.show();
		}
	};

}
